﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AutoCooker5
{
    public delegate void CookStartedReply();
    public delegate void CookProgressingReply();
    public delegate int CookCompletedReply();

    class AutoCooker5
    {
        // enent关键字在委托的外边包装了一个 property，仅让 C#客户通过 += 和 -=操作符来添加和移除，不能直接激发事件。
        public event CookStartedReply started;
        public event CookProgressingReply progressing;
        public event CookCompletedReply completed;

        public void DoCook()
        {
            Console.WriteLine("AutoCooker start to cook");
            if (started != null) started();

            Console.WriteLine("AutoCooker is cooking");
            if (progressing != null) progressing();

            Console.WriteLine("AutoCooker finish to Cook");
            if (completed != null)
            {
                // 更加苛刻的情况是这样的，Mother和Son有自己的事情要做，也就是说，委托调用的时间比较长，
                // 假设Son的CookCompleted动作，sleep 3秒，Mother的CookCompleted动作Sleep8秒；DoWork()的CookCompleted动作Sleep1秒。
                System.Threading.Thread.Sleep(1000);

                // 为了受到每个反馈，
                // 深入到代理里面，轮询监听者列表，手工一个个调用：
                foreach (CookCompletedReply item in completed.GetInvocationList())
                {
                    int grade = item();
                    Console.WriteLine("My appetite is {0} %", grade);           
                }
            }
        }
    }
}
